package org.jcc.core.cs;

public class Sqrt {
	public static void main(String[] args) {
		System.out.println(sqrt(2));
	}

	public static double sqrt(double x) {
		return tryGuess(x, 1);
	}

	private static double tryGuess(double x, double guess) {
		if (goodEnough(x, guess)) {
			return guess;
		} else {
			return tryGuess(x, improveGuess(x, guess));
		}
	}

	private static double improveGuess(double x, double guess) {
		return (guess + x / guess) / 2;
	}

	private static boolean goodEnough(double x, double guess) {
		return Math.abs(guess * guess - x) < 0.001;
	}
}
